package com.ycsj.goldmedalnewconcept.teacher.adapter;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.ycsj.common.base.SpKeys;
import com.ycsj.common.image.ImageUtil;
import com.ycsj.common.manager.CustomDialogManager;
import com.ycsj.common.manager.PopUpManager;
import com.ycsj.common.utils.DateUtils;
import com.ycsj.common.utils.GsonUtil;
import com.ycsj.common.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.R;
import com.ycsj.goldmedalnewconcept.common.Constants;
import com.ycsj.goldmedalnewconcept.common.HttpAddress;
import com.ycsj.goldmedalnewconcept.common.bean.ResultInfo;
import com.ycsj.goldmedalnewconcept.common.http.HttpUtils;
import com.ycsj.goldmedalnewconcept.common.util.AccountUtils;
import com.ycsj.goldmedalnewconcept.teacher.bean.AttenInfo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

/**
 * 考勤管理列表的数据适配器
 * Created by Administrator on 2019/3/29 0029.
 */

public class AttendanceRvAdapter extends BaseQuickAdapter<AttenInfo.ListBean, BaseViewHolder> {

    private Activity activity;

    private Context context;

    private Handler handler;

    public AttendanceRvAdapter(Context context, int layoutResId, @Nullable List<AttenInfo.ListBean> data) {
        super(layoutResId, data);
        this.context = context;
        this.activity = (Activity) context;
        handler = new Handler();
    }

    @Override
    protected void convert(final BaseViewHolder helper, final AttenInfo.ListBean item) {

        //头像
        RoundedImageView lvHead = helper.getView(R.id.iv_head);
        ImageUtil.displayImage(context, lvHead, item.getIcon(), R.drawable.head_default);

        //姓名
        TextView tvName = helper.getView(R.id.tv_name);
        tvName.setText(item.getName());

        //状态部分

        //已到
        TextView tvYd = helper.getView(R.id.tv_yd);

        //已到
        TextView tvCd = helper.getView(R.id.tv_cd);

        //请假
        TextView tvQj = helper.getView(R.id.tv_qj);

        //旷到
        TextView tvKd = helper.getView(R.id.tv_kd);


        //请假部分
        RelativeLayout rlQj = helper.getView(R.id.rl_qj);

        //有请假条状态下显示的请假批准状态和处理按钮
        TextView tvState = helper.getView(R.id.tv_state);

        //处理按钮
        ImageView lvCl = helper.getView(R.id.lv_cl);


        //处理逻辑:先判断请假信息,请假批准状态下,tvState显示已批准,tvQJ设置为白色,背景设置为tv_state_qj_select
        if ("1".equals(item.getIsPermission())) {
            //请假已批准状态
            tvQj.setTextColor(context.getResources().getColor(R.color.white));
            tvQj.setBackgroundResource(R.drawable.tv_state_qj_select);
            //设置请假的状态的文字为已批准
            rlQj.setVisibility(View.VISIBLE);
            tvState.setVisibility(View.VISIBLE);
            tvState.setText("已批准");
            tvState.setTextColor(context.getResources().getColor(R.color.tv_pj));
            //处理按钮隐藏
            lvCl.setVisibility(View.INVISIBLE);
            tvYd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvYd.setBackgroundResource(R.drawable.tv_state_qj_normal);
            tvCd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvCd.setBackgroundResource(R.drawable.tv_state_qj_normal);
            tvKd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvKd.setBackgroundResource(R.drawable.tv_state_qj_normal);

            //所有按钮不可交互
            setClickState(tvYd, tvCd, tvQj, tvKd, false);

        } else if ("0".equals(item.getIsPermission())) {
            //请假未批准

            //处理按钮隐藏
            rlQj.setVisibility(View.VISIBLE);
            lvCl.setVisibility(View.VISIBLE);
            tvState.setVisibility(View.VISIBLE);
            tvState.setText("请求批假");
            tvState.setTextColor(context.getResources().getColor(R.color.tv_no_pj));

            //所有按钮可交互
            setClickState(tvYd, tvCd, tvQj, tvKd, true);

            //同步状态
            sysState(tvYd, tvCd, tvQj, tvKd, 0, 0, 0, 0);

            //同步状态
            sysStateByAttendanceType(item, tvYd, tvCd, tvQj, tvKd);

        } else {
            //没有请假信息时处理按钮和显示请假状态的TextView都不显示
            rlQj.setVisibility(View.GONE);
            lvCl.setVisibility(View.GONE);
            tvState.setVisibility(View.GONE);

            //所有按钮可交互
            setClickState(tvYd, tvCd, tvQj, tvKd, true);

            //没有请假信息,根据服务器返回的已到,迟到,请假,旷到的状态来设置背景
            sysStateByAttendanceType(item, tvYd, tvCd, tvQj, tvKd);

        }

        //设置点击事件
        //已到的点击事件
        tvYd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sysBeanState(item, "0", helper.getLayoutPosition());
            }
        });

        //迟到的点击事件
        tvCd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sysBeanState(item, "1", helper.getLayoutPosition());
            }
        });

        //请假的点击事件
        tvQj.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sysBeanState(item, "2", helper.getLayoutPosition());

            }
        });

        //旷到的点击事件
        tvKd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sysBeanState(item, "3", helper.getLayoutPosition());
            }
        });


        //处理按钮的点击事件
        lvCl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //弹出处理请假批准的弹框

                showPerMitPop(item, helper.getLayoutPosition());
            }
        });

    }

    /**
     * 批假的弹框
     *
     * @param item
     */
    private void showPerMitPop(final AttenInfo.ListBean item, final int pos) {
        PopUpManager.showPop(context, R.layout.pop_leave_online, 0.3f, activity, new PopUpManager.onGetViewListener() {

            @Override
            public void getChildView(View view, int layoutResId) {

                //获取请假的列表
                List<AttenInfo.ListBean.LeaveListBean> leaveList = item.getLeaveList();

                final AttenInfo.ListBean.LeaveListBean leaveInfo = leaveList.get(0);

                //头像
                RoundedImageView lvHead = view.findViewById(R.id.iv_head);
                ImageUtil.displayImage(context, lvHead, item.getIcon(), R.drawable.head_default);

                //姓名
                TextView tvName = view.findViewById(R.id.tv_name);
                tvName.setText(item.getName());

                //请假时间
                TextView tvDate = view.findViewById(R.id.tv_date);

                //拼接请假时间
                String time = getTime(leaveInfo.getBeginDateStr()) + "~" + getTime(leaveInfo.getEndDateStr());
                tvDate.setText(time);


                //请假事由
                TextView tvReason = view.findViewById(R.id.tv_reason);
                tvReason.setText(leaveInfo.getContent());

                //创建时间
                TextView tvTime = view.findViewById(R.id.tv_time);
                tvTime.setText(DateUtils.getTime(leaveInfo.getCreateDateStr(), "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm"));

                //批准
                Button btPz = view.findViewById(R.id.bt_pz);

                //联系家长
                Button btLxjz = view.findViewById(R.id.bt_lxjz);

                //批准按钮点击事件
                btPz.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        doRatifyAction(item, pos, leaveInfo.getRowId() + "");
                    }
                });

                //联系家长按钮的点击事件
                btLxjz.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        if ("0".equals(SPUtil.getString(context, SpKeys.DISABLEGROUP))) {
                            ToastUtils.showShort("请用微信或者电话与家长沟通哦");
                            return;
                        } else if ("1".equals(SPUtil.getString(context, SpKeys.DISABLEGROUP))) {
                            //关闭弹框
                            PopUpManager.dismiss();
                            //调用系统拨号
                            if (!TextUtils.isEmpty(item.getSttel())) {
                                String phone = item.getSttel().toString().trim();
                                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            }
                        }
                    }
                });

            }
        });
    }


    /**
     * 批准
     */
    private void doRatifyAction(final AttenInfo.ListBean item, final int pos, String rowId) {

        //关闭弹框
        PopUpManager.dismiss();

        CustomDialogManager.show(context, "批准中...");

        Map<String, String> map = new HashMap<>();
        map.put("type", "4");
        map.put("acc", AccountUtils.getAccount(context));
        map.put("apptoken", AccountUtils.getToken(context));
        map.put("rowId", rowId);
        map.put("platform", "2");

        HttpUtils.post(HttpAddress.TEACHERLEAVELIST, map, this, new HttpUtils.CallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                CustomDialogManager.dissmiss();
                ToastUtils.showShort("批准失败,服务器异常");
            }

            @Override
            public void onResponse(String response, int id) {
                CustomDialogManager.dissmiss();
                if (!TextUtils.isEmpty(response)) {
                    ResultInfo info = null;
                    try {
                        info = GsonUtil.jsonToBean(response, ResultInfo.class);
                    } catch (Exception e) {
                        Log.i("test", Constants.PARSEDATAERROR);
                    }

                    if (null != info) {
                        if ("200".equals(info.getState()) || "102002".equals(info.getState())) {
                            //返回成功
                            //已批准状态
                            item.setIsPermission("1");
                            item.setAttendanceType("2");
                            notifyRefresh(pos);
                            ToastUtils.showShort("批准成功");
                        } else if ("102002".equals(info.getState())) {
                            ToastUtils.showShort("批准失败,推送异常");
                        } else {
                            ToastUtils.showShort("批准失败,返回异常码是:" + info.getState());
                            Log.i("test", Constants.ERRORSTATE + info.getState());
                        }
                    } else {
                        Log.i("test", Constants.EMPTY);
                    }
                } else {
                    Log.i("test", Constants.EMPTY);
                }
            }
        });

    }

    /**
     * 在item点击事件中直接使用notifyDataSetChanged()
     * 解决java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling
     *
     * @param pos
     */
    private void notifyRefresh(final int pos) {
        Runnable r = new Runnable() {
            public void run() {
                notifyItemChanged(pos);
            }
        };
        handler.post(r);
    }

    /**
     * 提供给Activity释放handler对象的方法,防止内存泄漏
     */
    public void releaseHandler() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    /**
     * 根据AttenInfo.ListBean item的ATTENDANCE_TYPE类型来同步状态
     *
     * @param item
     * @param tvYd
     * @param tvCd
     * @param tvQj
     * @param tvKd
     */
    private void sysStateByAttendanceType(AttenInfo.ListBean item, TextView tvYd, TextView tvCd, TextView tvQj, TextView tvKd) {
        if ("0".equals(item.getAttendanceType())) {
            //已到选中
            sysState(tvYd, tvCd, tvQj, tvKd, 1, 0, 0, 0);
        } else if ("1".equals(item.getAttendanceType())) {
            //迟到选中
            sysState(tvYd, tvCd, tvQj, tvKd, 0, 1, 0, 0);
        } else if ("2".equals(item.getAttendanceType())) {
            //请假选中
            sysState(tvYd, tvCd, tvQj, tvKd, 0, 0, 1, 0);
        } else if ("3".equals(item.getAttendanceType())) {
            //旷到选中
            sysState(tvYd, tvCd, tvQj, tvKd, 0, 0, 0, 1);
        } else {
            //都不选中
            sysState(tvYd, tvCd, tvQj, tvKd, 0, 0, 0, 0);
        }
    }


    /**
     * 点击四种状态后同步数据的方法
     *
     * @param item
     * @param pos
     */
    private void sysBeanState(AttenInfo.ListBean item, String state, int pos) {
        item.setAttendanceType(state);
        notifyItemChanged(pos);
    }

    /**
     * 设置几个状态的TextView是否是否可以点击
     *
     * @param tvYd
     * @param tvCd
     * @param tvQj
     * @param tvKd
     * @param canClick
     */
    private void setClickState(TextView tvYd, TextView tvCd, TextView tvQj, TextView tvKd, boolean canClick) {
        tvYd.setEnabled(canClick);
        tvCd.setEnabled(canClick);
        tvQj.setEnabled(canClick);
        tvCd.setEnabled(canClick);
    }

    /**
     * 同步状态的方法
     *
     * @param tvYd
     * @param tvCd
     * @param tvQj
     * @param tvKd
     * @param ydState 已到的状态 0没选中  1选中
     * @param cdState 迟到的状态 0没选中  1选中
     * @param qjState 请假的状态 0没选中  1选中
     * @param kdState 旷到的状态 0没选中  1选中
     */
    private void sysState(TextView tvYd, TextView tvCd, TextView tvQj, TextView tvKd, int ydState, int cdState, int qjState, int kdState) {
        if (0 == ydState) {
            tvYd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvYd.setBackgroundResource(R.drawable.tv_state_qj_normal);
        } else if (1 == ydState) {
            tvYd.setTextColor(context.getResources().getColor(R.color.white));
            tvYd.setBackgroundResource(R.drawable.tv_state_select);
        }


        if (0 == cdState) {
            tvCd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvCd.setBackgroundResource(R.drawable.tv_state_qj_normal);
        } else if (1 == cdState) {
            tvCd.setTextColor(context.getResources().getColor(R.color.white));
            tvCd.setBackgroundResource(R.drawable.tv_state_select);
        }


        if (0 == qjState) {
            tvQj.setTextColor(context.getResources().getColor(R.color.coffee));
            tvQj.setBackgroundResource(R.drawable.tv_state_qj_normal);
        } else if (1 == qjState) {
            tvQj.setTextColor(context.getResources().getColor(R.color.white));
            tvQj.setBackgroundResource(R.drawable.tv_state_select);
        }

        if (0 == kdState) {
            tvKd.setTextColor(context.getResources().getColor(R.color.coffee));
            tvKd.setBackgroundResource(R.drawable.tv_state_qj_normal);
        } else if (1 == kdState) {
            tvKd.setTextColor(context.getResources().getColor(R.color.white));
            tvKd.setBackgroundResource(R.drawable.tv_state_select);
        }
    }

    /**
     * 将服务器返回的2019-04-12格式化为2019年04月12日
     *
     * @param timeString
     * @return
     */
    private String getTime(String timeString) {
        String res = null;
        try {
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            Date mDate = sf.parse(timeString);
            //格式化
            SimpleDateFormat formatDateTime = new SimpleDateFormat("yyyy年MM月dd日");
            res = formatDateTime.format(mDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return res;
    }
}
